<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Base Omifk library
 *
 * PHP version 5.2
 *
 * @category Frameworks
 * @package  Omifk
 * @author   Claudio Beatrice <claudi0.beatric3@gmail.com>
 * @license  http://www.php.net/license/3_01.txt  PHP License 3.01
 * @version  SVN: $Id$
 * @link     http://www.silent-voice.org/
 */

/**
 * Loop on all the files in the Module directory, try to include them
 * and launch the main hook.
 *
 * @return void
 */
function omifk_modules_loop() {
    // Open module directory
    $handle = opendir(OMIFK_DIRECTORY_MODULES);
    // If it exists and it is browsable
    if ($handle) {
        // Loop on every file and directory
        while (false !== ($module_filename = readdir($handle))) {
            // If the considered one doesn't start with '.' then include the module
            if (strpos($module_filename, '.') !== 0) {
                omifk_include_module(str_replace('.php', '', $module_filename));
            }
        }
        // Close directory handler
        closedir($handle);
        // Route the request to the proper module
        omifk_route_request();
    } else {
        watchdog(
            t(
                'Can\'t open directory !module_directory',
                array('!module_directory' => OMIFK_DIRECTORY_MODULES)
            ),
            WATCHDOG_ERROR
        );
    }
}

/**
 * Return the list of supported hooks
 *
 * @return array containing supported hooks
 */
function omifk_list_hooks() {
    return array(
        'main',
        'help',
        'argv',
    );
}

/**
 * Check if a module is requested a run it
 *
 * @param $params array containing map of params
 *
 * @return null
 */
function omifk_route_request() {
    $params      = omifk_get_params();
    $module_name = akh_get($params, 'm', 'core');
    $hook_name   = akh_get($params, 'h', 'main');

    if (omifk_check_module($module_name)) {
        omifk_run_module($module_name, $hook_name);
    }
}

/**
 * Run a module by calling its entry point
 *
 * @param $module_name string containing module's name
 *
 * @return null
 */
function omifk_run_module($module_name, $hook_name = 'main') {
    $module_main_hook = $module_name . '_' . $hook_name;
    if (function_exists($module_main_hook)) {
        call_user_func($module_main_hook);
    } else {
        watchdog(
            t(
                'Module !module_filename doesn\'t implement main_hook',
                array('!module_filename' => $module_name)
            ),
            WATCHDOG_ERROR
        );
    }
}

/**
 * Check if a module exits and if it has a config file
 *
 * @param $module_name string containing module's name
 *
 * @return boolean
 */
function omifk_check_module($module_name) {
    $module_filename_prefix = OMIFK_DIRECTORY_MODULES . $module_name . '/' . $module_name;
    $module_filename        = $module_filename_prefix . '.module';
    $module_config_filename = $module_filename_prefix . '.info';

    if (file_exists($module_filename)) {
        if (file_exists($module_config_filename)) {
            return true;
        } else {
            watchdog(
                t(
                    'Module !module_filename doesn\'t have a configuration file',
                    array('!module_filename' => $module_name)
                ),
                WATCHDOG_NOTICE
            );
            return true;
        }
    } else {
        watchdog(
            t(
                'Module !module_filename doesn\'t exist',
                array('!module_filename' => $module_name)
            ),
            WATCHDOG_ERROR
        );
        return false;
    }
}

/**
 * Include a module
 *
 * @param string $module_name string containing module name
 *
 * @return boolean true if module's been loaded succesfully
 */
function omifk_include_module($module_name) {
    global $omifk_config;

    $module_filename_prefix = OMIFK_DIRECTORY_MODULES . $module_name . '/' . $module_name;
    $module_filename        = $module_filename_prefix . '.module';
    $module_config_filename = $module_filename_prefix . '.info';

    $omifk_config = array_merge($omifk_config, array($module_name => parse_ini_file($module_config_filename, true)));

    $ret = (boolean)(akh_get_recursive($omifk_config, array($module_name, 'active'), true)) ?
        (file_exists($module_filename) ? include_once $module_filename : false) :
        true;

    if (!$ret) {
        watchdog(
           t(
               'Error loading module !module_filename',
               array('!module_filename' => $module_name)
           ),
           WATCHDOG_ERROR
        );
    }

    return $ret;
}

/**
 * Return the absolute path of a module
 *
 * @param string $module_name string containing module name
 *
 * @return string containing absolute module's path
 */
function omifk_get_module_path($module_name) {
   return OMIFK_DIRECTORY_MODULES . $module_name . '/';
}

/**
 * Return module configuration
 *
 * @param string $module_name string containing module name
 *
 * @return array containing module's configuration
 */
function omifk_read_module_config($module_name) {
    global $omifk_config;

    return akh_get($omifk_config, $module_name, array());
}

/**
 * Return http query params
 *
 * @param string $param name of the wanted param
 * @param mixed $default a default value in case of failure
 *
 * @return the requeste param
 */
function omifk_get_param($param, $default = null) {
  return akh_get(omifk_get_params(), $param, $default);
}

/**
 * Return http query params
 *
 * @return array containing map of params
 */
function omifk_get_params() {
    static $params = array();

    if (empty($params)) {
        $params = omifk_parse_params();
    }

    return $params;
}

/**
 * Map query string or command line params into an array
 *
 * @return array containing map of params
 */
function omifk_parse_params() {
    global $argv;
    $params = array();

    if (empty($argv)) {
        // if using mod_php
        $tmp  = explode('&', akh_get_recursive($_SERVER, array('argv', 0)));
        $len  = count($tmp);
        $i    = -1;

        while (++$i < $len) {
            $tmp2 = explode('=', $tmp[$i]);
            $params[akh_get($tmp2, 0, $i)] = akh_get($tmp2, 1);
        }
    } else {
        // if using php cli
        $tmp = array_slice($argv, 1);
        while ($arg = array_shift($tmp)) {
            $params[ltrim($arg, '-')] = array_shift($tmp);
        }
    }

    return $params;
}

/**
 * Autoload a class if it exists and respect the naming convention
 *
 * @param string $class_name name of the class to try to autoload
 */
function __autoload($class_name) {
  require_once(str_replace('_', '/', $class_name) . '.php');
}
